using System.Linq;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;

namespace Common.Unity.Extensions.Entity
{
	static class SingleEntityRetrievalHelper
	{
		public static ItemType Resolve<ItemType>( ObjectQuery<ItemType> query, EntityKey key )
		{
			ItemType result = query.Where( ResolvePredicateText( query.Name, key ), ResolvePredicateParameters( key ) ).FirstOrDefault();
			return result;
		}

		static string ResolvePredicateText( string name, EntityKey key )
		{
			string[] parts = ( from item in key.EntityKeyValues select string.Format( "{0}.{1} = @{1}", name, item.Key ) ).ToArray();
			string result = string.Join( " AND ", parts );
			return result;
		}
		
		static ObjectParameter[] ResolvePredicateParameters( EntityKey key )
		{
			List<ObjectParameter> list = new List<ObjectParameter>();
			foreach ( EntityKeyMember member in key.EntityKeyValues )
			{
				list.Add( new ObjectParameter( member.Key, member.Value ) );
			}
			return list.ToArray();
		}
	}
}